/**
 * @Title: InitDataSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: 初始化应用信息
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月27日15:40:30
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.beans.VersionBean;
import com.jason.fingerprint.common.FileHelper;
import com.jason.fingerprint.utils.FileUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;

/**
 * @ClassName: App 下载
 * @Description: 版本下载
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-5-22 16:31:27
 */
public class DownloadSyncLogic extends Thread {

	private static final String TAG = "DownloadSyncLogic";

	final static int HTTP_STATUS_OK = 200;
	final static int HTTP_STATUS_PARTIAL_CONTENT = 206;

	/** 重试次数*/
	static int TIMEOUT_REPEAT_TIME = 2;
	/** 超时时间*/
	final static int CONNECT_TIME_OUT = 10*1000;

	/** 暂停*/
	private boolean mIsPause = false;
	/** 缓冲区大小*/
	private static final int BUFFER_SIZE = 1024*100;
	/** 移动网络缓冲区大小*/
	private static final int GPRS_BUFFER_SIZE = 1024*100;
	/** Wifi缓冲区大小*/
	private static final int WIFI_BUFFER_SIZE = 1024;
	/** 当前连接*/
	private HttpURLConnection mHttpConnection;

	private boolean mError;

	private VersionBean mVersionBean;

	private Context mContext;

	private Handler mHandler;

	public DownloadSyncLogic(){

	}

	public DownloadSyncLogic(VersionBean versionBean){
		this.mVersionBean = versionBean;
		this.mContext = AppContext.getAppContext();
	}

	public DownloadSyncLogic(VersionBean versionBean,Handler handler){
		this.mVersionBean = versionBean;
		this.mContext = AppContext.getAppContext();
		this.mHandler = handler;
	}

	public void run(){
		TIMEOUT_REPEAT_TIME = 2;
		doDownload();
	}

	private void doDownload(){
		InputStream is =null;
		RandomAccessFile raf = null;
		String fileName = "FingerPrint" + mVersionBean.getVersionNum();
		if(mVersionBean != null && mVersionBean.getType() == 1){
			fileName = "FireFox";
		}
		String tmpSavePath = FileHelper.getAppRootDir(mContext) + "/" + fileName  + ".tmp";
		String savePath = FileHelper.getAppRootDir(mContext) + "/" + fileName + ".apk";
		Log.i(TAG, "doDownload tmpSavePath:" + tmpSavePath);
		Log.i(TAG, "doDownload savePath:" + savePath);
		try {
			Log.i(TAG, "start download:"+ mVersionBean.getPosition());
			String url = mVersionBean.getPosition();
			Log.i(TAG," doDownload 001  url :" + url);
			url = url.replace("&amp;","&");
			Log.i(TAG," doDownload 002  url :" + url);
			URL downUrl = new URL(url);
			mHttpConnection = (HttpURLConnection) downUrl.openConnection();
			mHttpConnection.setConnectTimeout(CONNECT_TIME_OUT);
			mHttpConnection.setRequestMethod("GET");
			mHttpConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
			mHttpConnection.setRequestProperty("Accept-Language", "en_US");
			mHttpConnection.setRequestProperty("Referer", downUrl.toString());
			mHttpConnection.setRequestProperty("Charset", "UTF-8");
			//设置获取实体数据的范围
			int startPos = FileUtils.getFileLength(tmpSavePath);
			mHttpConnection.setRequestProperty("Range", "bytes=" + startPos + "-");
			mHttpConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
			mHttpConnection.setRequestProperty("Connection", "Keep-Alive");

			if (mHttpConnection.getResponseCode() == HTTP_STATUS_OK
					|| mHttpConnection.getResponseCode() == HTTP_STATUS_PARTIAL_CONTENT){
				if (mHttpConnection.getHeaderField("content-length") != null){
					int leftLength = Integer.parseInt(mHttpConnection.getHeaderField("content-length"));
					int fileLength = startPos+leftLength;
				}

				is = mHttpConnection.getInputStream();
				byte[] buffer = new byte[WIFI_BUFFER_SIZE];
				int offset = 0;

				File tmpFile = FileUtils.createFile(tmpSavePath);
				raf = new RandomAccessFile(tmpFile, "rwd");
				raf.seek(startPos);
				long lastTime = System.currentTimeMillis();
				int lastOffset = 0;
				StringBuffer speed = new StringBuffer();
				while ((offset = is.read(buffer, 0, WIFI_BUFFER_SIZE)) != -1) {
					raf.write(buffer, 0, offset);
					lastOffset += offset;
					if (System.currentTimeMillis()-lastTime >= 1000){
						speed.delete(0, speed.length());
						lastTime = System.currentTimeMillis();
						lastOffset = 0;
					}
					pause();
				}
				raf.close();
				is.close();
				mHttpConnection.disconnect();
				FileUtils.renameTo(tmpSavePath, savePath);
				//更新数据,下载结果回调
				//下载完成
				Message message = new Message();
				message.obj = savePath;
				mHandler.handleMessage(message);
				downloadFinish(savePath);
			} else{
				Log.e(TAG, "download failed with reponseCode of server:"+mHttpConnection.getResponseCode());
				mHandler.obtainMessage(1);
			}
		} catch (SocketTimeoutException e) {
			Log.e(TAG, "", e);
			if (--TIMEOUT_REPEAT_TIME >= 0){
				doDownload();
			} else{
				mError = true;
				mHandler.obtainMessage(1);
			}
		} catch (SocketException e){
			Log.e(TAG, "", e);
			mError = true;
			mHandler.obtainMessage(1);
		} catch (IOException e){
			Log.e(TAG, "", e);
			mError = true;
			mHandler.obtainMessage(1);
		} catch (Exception e){
			Log.e(TAG, "", e);
			mError = true;
			mHandler.obtainMessage(1);
		}finally{
			try {
				if(raf!=null){
					raf.close();
				}
				if(is!=null){
					is.close();
				}
				if(mHttpConnection!=null){
					mHttpConnection.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	protected void downloadFinish(String saveFileName){
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		mContext.startActivity(i);
	}

	/**
	 * 暂停下载
	 */
	protected void pause() {
		if (mIsPause) {
			synchronized (this) {
				try {
					this.wait();
				} catch (InterruptedException e) {}
			}
		}
	}

	/**
	 * 强制停止下载
	 */
	protected void stopDownload(){
		if(mHttpConnection != null) {
			mHttpConnection.disconnect();
			mHttpConnection = null;
		}
	}

	public boolean isPause() {
		return mIsPause;
	}

	public void setPause(boolean isPause) {
		this.mIsPause = isPause;
	}

	public boolean getThreadError() {
		return mError;
	}


}
